package com.tbs.parkingsaleapp.SystemManager;

import abstergo.tbs.betterasyc.Handler.HandlerMananger;
import abstergo.tbs.betterasyc.Handler.IHandlerAction;
import android.content.Context;
import android.os.Message;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import com.tbs.parkingsaleapp.Http.AsycHttp;
import com.tbs.parkingsaleapp.Http.HttpHelper;
import com.tbs.parkingsaleapp.Http.IAsycHttpBackgroundAction;
import com.tbs.parkingsaleapp.Http.IAsycHttpResultAction;
import com.tbs.parkingsaleapp.Http.JsonData.Houseinfo;
import com.tbs.parkingsaleapp.Http.JsonData.LocationInfo;
import com.tbs.parkingsaleapp.Http.JsonData.LoginResult;
import com.tbs.parkingsaleapp.Http.JsonData.ParkResult;
import com.tbs.parkingsaleapp.Http.Listenner.LocationInfosHttper;
import com.tbs.parkingsaleapp.SystemManager.FileMananger.LittleDataMananger;
import com.tbs.parkingsaleapp.SystemManager.Handler.CallBacks.ParkDataUpdater;
import com.tbs.parkingsaleapp.SystemManager.Handler.HandlerConst;
import com.tbs.parkingsaleapp.UI.FaceTakeActivity;
import com.tencent.tencentmap.mapsdk.maps.model.Marker;

import java.util.*;

public class SystemDataMananger {
    private static final String KEY_PERPAGENUMBER = "PERPAGENUMBER";

    private static int perpage=5;
    public static HashMap<Integer,Marker> markers=new HashMap<>();
    private static final   String LOGINDATA = "logined",LOGINDATA_ID = "logined_id";
    private static boolean isFirst=true;

    public static boolean isFirst() {
        return isFirst;
    }

    public static void FillData(Context context,boolean force)
    {
        for (Marker i: SystemDataMananger.markers.values()
        ) {
            i.remove();
        }
        SystemDataMananger.markers.clear();
        SystemDataMananger.ClearLocations();
        LocationInfosHttper httper=new LocationInfosHttper(force);
        AsycHttp<String, LocationInfo[]> req=new AsycHttp<String,LocationInfo[]>().setBackgroundAction(httper).setResultAction(httper).setContext(context);
        req.execute();
    }


    //以小区id为key
    private static HashMap<Integer, ArrayList<ParkResult>> parks=new HashMap<>();
    //以小区id为key
    private static HashMap<Integer,LocationInfo> locations=new HashMap<>();


    public static void ClearParks()
    {
        parks.clear();
    }
    public static void ClearParkFromLocation(int i)
    {
        if(parks.containsKey(i))
            parks.get(i).clear();
    }
    public static void ClearLocations()
    {
        locations.clear();
    }

    public static ArrayList<ParkResult> FindAllParks(int l)
    {
        if(parks.containsKey(l))
            return parks.get(l);
        else
            return new ArrayList<>();
    }
    public static Collection<LocationInfo> AllLocations()
    {
        return locations.values();
    }
    public static LocationInfo FindLocation(int l)
    {
        if(locations.containsKey(l))
            return locations.get(l);
        else
            return null;
    }


    public static void AppendLocationInfoCache(LocationInfo[] infos)
    {
        for (LocationInfo i:infos
             ) {
            locations.put(i.getLocation().getId(),i);
        }
    }
    public static void AppendParkCache(ParkResult[] ps)
    {
        for (ParkResult i:ps
             ) {
            ArrayList<ParkResult> arr=parks.get(i.getPark().getLocation());
            if(arr==null)
                arr=new ArrayList<>();
            arr.add(i);
            parks.put(i.getPark().getLocation(),arr);
        }
    }

    public static boolean Buyable(ParkResult park)
    {
        if(park.getPark().getStatus()!=1)
        {
            return false;
        }
        if(isLogined())
        {
            LoginResult user=getLogined();
            boolean isin=false;
            for (Houseinfo h: user.getHouseinfo()
                 ) {
                if(h.getLocation().getId()==park.getPark().getLocation())
                {
                    isin=true;
                    break;
                }
            }
            return isin||park.getTrait().getIsOpenForSale();

        }
        else
        {
            return false;
        }
    }
    private static void LoginMsgSend()
    {
        HandlerMananger.Instance().SendMsg(HandlerMananger.MakeMsg(HandlerConst.LOGINED));
    }
    private static LoginResult Logined;
    public static boolean isLogined()
    {
        return  Logined!=null;
    }
    public static void Login(LoginResult result,boolean isRemmber,Context context)
    {
        Logined=result;
        LittleDataMananger.SaveBoolean(context,LOGINDATA, isRemmber);
        if(isRemmber)
            LittleDataMananger.SaveString(context,LOGINDATA_ID,result.getUserinfo().getId());
        LoginMsgSend();
    }
    public static void OutLogin(Context context)
    {
        Logined=null;
        LittleDataMananger.SaveBoolean(context,LOGINDATA,false);
        LoginMsgSend();
    }

    private static void init_doSomeThing(Context context)
    {
        if(LittleDataMananger.ReadBool(context,LOGINDATA))
        {
            AsycHttp<String,LoginResult> http=new AsycHttp<>();
            http.setContext(context).setBackgroundAction(new IAsycHttpBackgroundAction<String, LoginResult>() {
                @Override
                public LoginResult BackGroundAction(String... params) throws Exception {
                    String id=LittleDataMananger.ReadString(context,LOGINDATA_ID);
                    String r=HttpHelper.Get(NetWorkSetting.UpdateUserDataUrl(id));
                    return JSON.parseObject(r,LoginResult.class);
                }
            }).setResultAction(new IAsycHttpResultAction<LoginResult>() {
                @Override
                public void ResultFunction(LoginResult result) {
                    Login(result,true,context);
                    Toast.makeText(context,"自动登录成功",Toast.LENGTH_SHORT).show();
                }
            }).execute();
        }
        else
            LoginMsgSend();
    }

    private static void init_subscribeSomething(Context context)
    {
        HandlerMananger.Subscribe(HandlerConst.SAFETOTAKE, new IHandlerAction() {
            @Override
            public void Handle(Message rawmsg) {
                FaceTakeActivity.safeToTakePicture=true;
            }
        },false);
        HandlerMananger.Subscribe(HandlerConst.TOAST_DELAY,new LoadToastMananger.LoadToastDelayer(),false);
        HandlerMananger.Subscribe(HandlerConst.TOAST_HIDE,new LoadToastMananger.LoadToastAutoHider(),false);
        HandlerMananger.Instance().Subscribe(HandlerConst.PARKDATAUPDATER,ParkDataUpdater.Instance(),false);
    }

    public static void Init(Context context)
    {
        init_subscribeSomething(context);
        init_doSomeThing(context);
    }

    public interface ISelectPark
    {
        boolean Select(ParkResult parkResult);
    }

    public static ArrayList<ParkResult> SelectingParking(ISelectPark selectPark,Comparator<ParkResult> sorter)
    {
        ArrayList<ParkResult> result=new ArrayList<>();
        for (ArrayList<ParkResult> pr: parks.values()
             ) {
            for (ParkResult r:pr
                 ) {
                if(selectPark.Select(r))
                    result.add(r);
            }
        }
        if(sorter!=null)
            result.sort(sorter);
        return result;
    }


    public  static LoginResult getLogined()
    {
        return  Logined;
    }
}

